# -*- coding:utf-8 -*-

from fastapi import APIRouter, Depends, Request
from fastapi.responses import FileResponse
from pathlib import Path
import json

from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from utils.response_util import ResponseUtil
from utils.log_util import logger

agentUpdateController = APIRouter(prefix='/agent/update', tags=['Agent更新管理'])

# Agent更新文件存储目录
AGENT_UPDATE_DIR = Path(__file__).parent.parent.parent / 'agent_updates'
AGENT_UPDATE_DIR.mkdir(exist_ok=True)


@agentUpdateController.get('/version')
async def get_latest_version(request: Request):
    """获取最新版本信息"""
    try:
        version_file = AGENT_UPDATE_DIR / 'latest_version.json'
        
        if not version_file.exists():
            # 返回默认版本信息
            return ResponseUtil.success(data={
                'version': '1.0.0',
                'build_time': '2025-01-01 00:00:00',
                'download_url': f'{request.base_url}agent/update/download/agent_1.0.0.tar.gz',
                'md5': '',
                'description': '初始版本',
                'force_update': False
            })
        
        with open(version_file, 'r', encoding='utf-8') as f:
            version_info = json.load(f)
        
        # 添加完整的下载URL
        if 'download_url' not in version_info or not version_info['download_url'].startswith('http'):
            filename = version_info.get('filename', f"agent_{version_info['version']}.tar.gz")
            version_info['download_url'] = f'{request.base_url}agent/update/download/{filename}'
        
        return ResponseUtil.success(data=version_info)
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@agentUpdateController.get('/download/{filename}')
async def download_update_file(filename: str):
    """下载更新文件"""
    try:
        file_path = AGENT_UPDATE_DIR / filename
        
        if not file_path.exists():
            return ResponseUtil.error(msg='文件不存在')
        
        return FileResponse(
            path=str(file_path),
            filename=filename,
            media_type='application/gzip'
        )
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@agentUpdateController.post(
    '/publish',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:update:publish'))]
)
async def publish_update(
    request: Request,
    version: str,
    filename: str,
    md5: str,
    description: str = '',
    force_update: bool = False
):
    """发布新版本"""
    try:
        version_info = {
            'version': version,
            'build_time': '',
            'filename': filename,
            'download_url': f'{request.base_url}agent/update/download/{filename}',
            'md5': md5,
            'description': description,
            'force_update': force_update
        }
        
        version_file = AGENT_UPDATE_DIR / 'latest_version.json'
        with open(version_file, 'w', encoding='utf-8') as f:
            json.dump(version_info, f, indent=2, ensure_ascii=False)
        
        logger.info(f"发布新版本: {version}")
        return ResponseUtil.success(msg='发布成功')
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))

